import { schemaRegister } from './joi.js'

import fs from 'fs'

const result = []

fs.readFile('new_template.json', 'utf-8', (err, data) => {
  if (err) {
    throw err
  }

  const value = JSON.parse(data).filter((el) => el.version === '2')
  const origin = value.map((el) => {
    try {
      const _origin = JSON.parse(el.origin)
      if ('createData' in _origin) {
        return {
          ...el,
          data: {
            campaign: _origin.createData.campaign.baseInfo,
            adgroup: _origin.createData.adgroup.baseInfo,
            adcreative: _origin.createData.adcreative.baseInfo
          }
        }
      } else {
        return {
          ...el,
          data: _origin
        }
      }
    } catch (err) {
      console.log({ id: el.id, user_id: el.user_id, name: el.name })
    }
  })
  origin.forEach((el) => {
    try {
      const value = el.data
      const isValid = schemaRegister.validate(value)
      if ('error' in isValid) {
        result.push({ id: el.id, name: el.name, error: true, detail: isValid })
      } else {
        result.push({ id: el.id, name: el.name, error: false, errorMsg: '' })
      }
    } catch (e) {
      result.push({ catch: true, msg: e, ...el })
    }
  })
  console.log(
    `总条数：${result.length}，错误条数：${result.filter((el) => el.error).length}，正确条数：${
      result.filter((el) => el.error === false).length
    }，catch 条数：${result.filter((el) => el.catch).length}`
  )

  fs.writeFile('result.json', JSON.stringify(result), (err) => {
    if (err) {
      throw err
    }
    console.log('JSON data is saved.')
  })
})

// const value = {
//   campaign: {
//     name: 'perfume_{{日期}}_{{时间}}_{{标识}}',
//     objective: 'OUTCOME_SALES',
//     buying_type: 'AUCTION',
//     special_ad_categories: ['NONE'],
//     is_budget_schedule_enabled: false,
//     status: 'ACTIVE',
//     bid_strategy: 'COST_CAP',
//     smart_promotion_type: 'GUIDED_CREATION',
//     budget_type: 'lifetime_budget',
//     lifetime_budget: '0'
//   }
// }

// const validate = schemaRegister.validate(value)
// console.log(validate)
// fs.writeFile('result.json', JSON.stringify(validate), () => {})
